use crate::util::get_vite_config_path;
use common::model::CodeModule;
use common::model::{ProjectConfig, ServerProxy};
use common::traits::{ObjectLitTrait, ViteConfigTrait, ViteConfigUpdatedModuleTrait};
use std::fs;
use std::path::Path;

pub fn apply_proxy(
    project_config: &ProjectConfig,
    project_dir: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    if let Some(proxies) = &project_config.proxies {
        let vite_config_path = &get_vite_config_path(project_dir);
        let mut vite_config = CodeModule::new(&fs::read_to_string(vite_config_path)?)?;
        vite_config.init_server_node()?;
        vite_config.init_proxy_node()?;

        for proxy in proxies {
            add_proxy(&mut vite_config, proxy)?;
        }

        fs::write(vite_config_path, vite_config.get_source())?;
    }
    Ok(())
}

fn add_proxy(
    vite_config: &mut CodeModule,
    proxy: &ServerProxy,
) -> Result<(), Box<dyn std::error::Error>> {
    if let Some(proxy_object) = vite_config.update_module()?.try_get_proxy_node() {
        if proxy_object
            .try_get_object_value(&proxy.route_name)
            .is_none()
        {
            vite_config.insert_proxy(proxy)?;
        } else {
            println!("proxy:{} 已存在，操作被跳过", &proxy.route_name);
        }
    }
    Ok(())
}
